package com.weng.platform.apiManager.doc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.weng.framework.common.model.component.tree.TreeGridBuilder;
import com.weng.framework.common.model.component.tree.TreeNode;
import com.weng.framework.core.constants.ResultCodeEnum;
import com.weng.framework.core.model.ResponseData;
import com.weng.framework.dao.mybatis.model.page.PageModel;
import com.weng.framework.dao.mybatis.service.BaseServiceImpl;
import com.weng.platform.apiManager.doc.entity.Catalog;
import com.weng.platform.apiManager.doc.mapper.CatalogMapper;
import com.weng.platform.apiManager.doc.model.vo.CatalogTreeNode;
import com.weng.platform.apiManager.doc.service.IApiDocService;
import com.weng.platform.apiManager.doc.service.ICatalogService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;


/**
 * api分类 服务实现类
 *
 * @author wengzhonghui
 * @date 2020-09-26 23:44:06
 *
 */ 
@Slf4j
@Service
public class CatalogServiceImpl extends BaseServiceImpl<CatalogMapper, Catalog> implements ICatalogService {
	@Autowired
	private CatalogMapper catalogMapper;
    @Autowired
	private IApiDocService apiDocService;
	
	public List<CatalogTreeNode> getTreeGridData(String name, String parentId, String isExpand, String projectId){

        Catalog queryObj = new Catalog();
        QueryWrapper<Catalog> wrapper = new QueryWrapper<Catalog>(queryObj);
        if(!StringUtils.isEmpty(name)){
            wrapper.like("name", name);
        }
				wrapper.eq("project_id", projectId);
				wrapper.orderByAsc("position");
        List<Catalog> data = catalogMapper.selectList(wrapper);
        List<CatalogTreeNode> list = new TreeGridBuilder<Catalog, CatalogTreeNode>(data)
                .build(new CatalogComparator(),new CatalogTreeNode(), false);
        if ("1".equals(isExpand)) {
            TreeNode.expandAllNodes(list);
        }
        TreeNode.expandNodesByDepth(list,2);
        return list;
    }

    private class CatalogComparator implements Comparator<Catalog> {
        @Override
        public int compare(Catalog o1, Catalog o2) {
            Integer depth1 = o1.getPosition();
            Integer depth2 = o2.getPosition();
            if(depth1==null || depth2==null){
                return 0;
            }else {
                return o1.getPosition().intValue() - o2.getPosition().intValue();
            }
        }
    }
	
	
	/**
	 * 分页查询api分类
	 * @return
	 */
	@Override
	public IPage<Catalog> list(Integer pageNo,Integer pageSize) {
		QueryWrapper<Catalog> qw = new QueryWrapper<>();
		IPage<Catalog> page = new PageModel<>(pageNo,pageSize);
		return catalogMapper.selectPage(page,qw);
	}


	/**
	 * 获取单个api分类
	 * @param id
	 * @return
	 */
	@Override
	public Catalog getById(Serializable id) {
		return super.getById(id);
	}

	/**
	 * 新增单个api分类
	 * @param catalog
	 * @return
	 */
	@Override
	public Catalog add(Catalog catalog)  {
		
		catalogMapper.insert(catalog);
		return catalog;
	}

	/**
	 * 更新单个api分类
	 * @param catalog
	 * @return
	 * @
	 */
	@Override
	public ResponseData update(Catalog catalog)  {
        if(catalog.getParentId() != null &&catalog.getParentId().equals(catalog.getId())){
            return ResponseData.failed(ResultCodeEnum.PARAM_VALID_FAIL.getCode(),"不能选择当前结点做为父结点！");
        }
        catalogMapper.updateById(catalog);
        return ResponseData.success();

	}


	@Override
    @Transactional
	public ResponseData removeByIds(String ids) {
		String[] catalogIds = ids.split(",");
		for(String catalogId : catalogIds){
            int apiDocCount = this.apiDocService.countByCatalogId(catalogId);
            if(apiDocCount > 0){
                Catalog catalog =  this.catalogMapper.selectById(catalogId);
                if(catalog != null){
                    return ResponseData.failed(catalog.getName() + " 有关联文档，不能删除!");
                }
            }
        }
		this.removeByIds(Arrays.asList(catalogIds));
        return ResponseData.success();
	}

}
